import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fishing/providers/version_provider.dart';
import 'package:fishing/widgets/version_update_dialog.dart';

/// 版本更新监听器
/// 监听版本更新状态，自动显示更新对话框
class VersionUpdateListener extends StatefulWidget {
  final Widget child;

  const VersionUpdateListener({
    super.key,
    required this.child,
  });

  @override
  State<VersionUpdateListener> createState() => _VersionUpdateListenerState();
}

class _VersionUpdateListenerState extends State<VersionUpdateListener> {
  bool _dialogShown = false;

  @override
  Widget build(BuildContext context) {
    return Consumer<VersionProvider>(
      builder: (context, versionProvider, child) {
        // 监听更新响应变化
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _handleUpdateResponse(versionProvider);
        });

        return widget.child;
      },
    );
  }

  void _handleUpdateResponse(VersionProvider versionProvider) {
    final updateResponse = versionProvider.updateResponse;
    
    // 暂时注释掉版本更新日志
    
    // 如果有更新且对话框未显示
    if (updateResponse != null && 
        updateResponse.hasUpdate && 
        !_dialogShown &&
        mounted) {
      
      _dialogShown = true;
      
      // 延迟显示对话框，确保Navigator已经初始化
      Future.delayed(const Duration(milliseconds: 100), () {
        if (mounted && Navigator.maybeOf(context) != null) {
          // 显示更新对话框
          VersionUpdateDialog.show(
            context,
            updateResponse,
            onCancel: () {
              _dialogShown = false;
              versionProvider.clearUpdateResponse();
            },
          ).then((_) {
            _dialogShown = false;
            versionProvider.clearUpdateResponse();
          }).catchError((error) {
            _dialogShown = false;
          });
        } else {
          // 如果Navigator还没准备好，重置状态
          _dialogShown = false;
        }
      });
    }
  }
}